package com.jcj.reconnheart;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;


/**
 * 客户端启动类
 */
public class AppClientReconnHeart {

    private final String host;
    private final int port;

    public AppClientReconnHeart(String host, int port) {
        this.host = host;
        this.port = port;
    }

    /**
     * 配置响应的参数,提供连接到远端的方法
     */
    public void run() throws Exception {
        //I/O线程池
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bs = new Bootstrap(); //客户端辅助启动类
            bs.group(group)
                    .channel(NioSocketChannel.class)  //实例化一个Channel
                    .remoteAddress(new InetSocketAddress(host, port)) //指定远端ip和端口
                    .handler(new ChannelInitializer<SocketChannel>() {  //进行通道初始化配置
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //超时检测的Handler(注意顺序这里必须写在自定义Handler前面)
                            socketChannel.pipeline().addLast(new IdleStateHandler(5, 0, 0, TimeUnit.SECONDS));

                            //添加我们自定义的Handler
                            socketChannel.pipeline().addLast(new HandlerClientReconnHeart());

                        }
                    });

            //连接到远程节点;等待连接完成
            ChannelFuture future = bs.connect();
            future.addListener(new ListenerClientReconnHeart());

            //每隔2秒,自动向服务器发送一条消息
            while (true) {
                Thread.sleep(6000);
                //设置日期格式
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String strDate = df.format(new Date());
                future.channel().writeAndFlush(Unpooled.copiedBuffer(strDate, CharsetUtil.UTF_8));
            }


            //阻塞操作,closeFuture()开启了一个channel的监听器(这期间channel在进行各项工作),直到链路断开
            //future.channel().closeFuture().sync();

        } finally {
            group.shutdownGracefully().sync();  //优雅的关闭资源
        }
    }

    public static void main(String[] args) throws Exception {

        new AppClientReconnHeart("127.0.0.1", 18081).run();
    }

}

























